import Vue from "vue";
import Vuex from "vuex";

//1.导入插件
import VuexPersistence from "vuex-persist";
//2. 创建对象进行配置
const vuexLocal = new VuexPersistence({
  storage: window.localStorage, //配置存储介质，默认持久化到本地存储中
});

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    m_token: "",
    m_user: {},
    cart_list:[],
    checked:true,
  },
  mutations: {
    //提交token和用户名
    dologin(state,users){
      state.m_token=users.token
      state.m_user=users
    },
    //退出
    loginout(state) {
      state.m_user = {};
      state.m_token = "";
    },
    //加入购物车的逻辑
    addcart(state,cart){
      //加入购物车
      state.cart_list.push(cart);
    },
    //执行删除
    remove(state,index){
      state.cart_list.splice(index,1);
    }
  },
  //计算属性
  getters:{
    //计算选中商品的总数量
    nums(state){
    return state.cart_list.reduce((pre,cur)=>{
        if(state.checked==true){
          pre+=cur.num;
        }
        return pre;
      },0)
    },

    //计算选中商品的总数量 
    totals(state){
      //计算总价格的变量
      let amounts = 0;
      //循环计算总价格
      state.cart_list.forEach(item=>{
        if(state.checked==true){
          amounts+=item.num*item.price; 
        }
      })
      return amounts;
    }
  },
  actions: {},
  plugins: [vuexLocal.plugin], //引入插件
});
